#include "filestream.h"
#include "log/EZQLOG.h"

FileStream::FileStream(const QString &filePath)
{
    _filePath = filePath;
    _file.setFileName(_filePath);
    open();
}
FileStream::~FileStream()
{
    if(_file.isOpen()){
        _file.close();
    }
}

int FileStream::open()
{
    if(!_file.open(QIODevice::ReadOnly)){
        _isEof = StreamBase_Error;
        _size = 0;
    }else{
        _isEof = StreamBase_end;
        _size = _file.size();
    }
    return _isEof;
}


qint64 FileStream::validFrom(qint64 offset)
{
    if(_isEof==StreamBase_Error){
        return 0;
    }
    if(offset>=0 && offset < _size){
        return _size - offset;
    }else{
        return 0;
    }
}

qint64 FileStream::read(void *buffer, qint64 offset, qint64 bufferLen)
{
    if(_isEof == -1){
        return 0;
    }
    if(offset<0 || offset > _size){
        return 0;
    }
    _file.seek(offset);
    int willReadLen = bufferLen>_size-offset? _size-offset:bufferLen;
    qint64 readLen = _file.read((char*)buffer,willReadLen);
    return readLen;
}
